package com.quectel.cms.controller.forum;


import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.business.common.mobileuser.MobileUserMsgBusiness;
import com.quectel.business.common.util.sys.SysCodeUtils;
import com.quectel.cms.controller.BaseController;
import com.quectel.cms.interceptor.LoginUserSession;
import com.quectel.cms.util.SessionHolder;
import com.quectel.cms.vo.forum.ForumAuditReq;
import com.quectel.constant.PushConstants;
import com.quectel.constant.core.mobileuser.MobileUserMsgConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.constant.global.annotation.RequirePermissions;
import com.quectel.constant.sys.SysCodeKeyConstants;
import com.quectel.core.module.forum.dto.mongo.ForumCommentDto;
import com.quectel.core.module.forum.service.mongo.ForumCommentService;
import com.quectel.core.module.forum.service.mongo.ForumPostService;
import com.quectel.core.module.household.dto.HouseholdDto;
import com.quectel.core.module.household.service.HouseholdService;
import com.quectel.core.module.mobileuser.dto.MobileUserDto;
import com.quectel.core.module.mobileuser.service.MobileUserService;
import com.quectel.core.module.village.service.VillageService;
import com.quectel.util.common.*;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @author zhangheng
 * @email nolan.zhang@quectel.com
 * @date 2023/05/10 11:21
 */
@RestController
@RequestMapping("forumComment")
@Tag(name = "ForumCommentController", description = "邻友圈帖子评论相关api")
public class ForumCommentController extends BaseController {

    @DubboReference
    private ForumPostService forumPostService;
    @DubboReference
    private HouseholdService householdService;
    @DubboReference
    private VillageService villageService;
    @DubboReference
    private MobileUserService mobileUserService;
    @DubboReference
    private ForumCommentService forumCommentService;

    @Autowired
    private MobileUserMsgBusiness mobileUserMsgBusiness;


    /**
     * 帖子列表
     *
     * @param
     * @return
     */

    @GetMapping("commentList")
    @Operation(summary = "评论列表查询")
    public Response<Page<ForumCommentDto>> commentList(
            @Parameter(description = "从1开始的页码数") @RequestParam Integer pageNo,
            @Parameter(description = "每页多少条") @RequestParam Integer pageSize,
            @Parameter(description = "帖子Id") @RequestParam(required = false) Long postId
    ) {
        if (postId == null) {
            return Response.<Page<ForumCommentDto>>ok().wrap(Page.empty(pageNo, pageSize));
        }

        Request request = Request.configParams(Request.parseParams(httpServletRequest));

        request.put(LambdaUtil.getFieldName(ForumCommentDto::getForumPostId), postId);
        //未删除的帖子
        request.put(LambdaUtil.getFieldName(ForumCommentDto::getDeletedFlag), SystemConstants.NO);

        request.put(SystemConstants.SORT_ORDER_RULE_KEY, SystemConstants.SORT_ORDER_RULE_DESC);

        int total = forumCommentService.queryTotal(request.getParams());
        List<ForumCommentDto> forumCommentDtos = null;
        if (total > 0) {
            forumCommentDtos = forumCommentService.queryList(request.getParams());

            forumCommentDtos.forEach(forumCommentDto -> {
                HouseholdDto householdDto = householdService.selectCacheById(forumCommentDto.getHouseholdId());
                if (householdDto != null && householdDto.getVillageDto() != null) {
                    forumCommentDto.setVillageName(householdDto.getVillageDto().getName());
                }
            });

        } else {
            forumCommentDtos = new ArrayList<>();
        }

        Page<ForumCommentDto> page = new Page<>(request.getPageNo(), request.getPageSize(), total, forumCommentDtos);
        return Response.<Page<ForumCommentDto>>ok().wrap(page);
    }

    /**
     * 批量删除
     *
     * @param forumAuditReq
     * @return
     */
    @PostMapping("delete")
    @RequirePermissions(values = "forumComment:delete")
    @Operation(summary = "根据多条记录id批量删除评论管理")
    public Response<Object> delete(@RequestBody ForumAuditReq forumAuditReq) {

        Map<String, Object> params = new HashMap<>();
        super.fillAuthorityData(params);

        for (Long id : forumAuditReq.getIds()) {

            params.remove(SystemConstants.ENTITY_ID_FLAG);
            params.put(SystemConstants.ENTITY_ID_FLAG, String.valueOf(id));

            if (forumCommentService.queryTotal(params) <= 0) {
                return Response.error(SystemConstants.ILLEGAL_MSG);
            }
        }

        LoginUserSession sysUser = SessionHolder.getSysUser();
        forumCommentService.auditDeleteBatch(sysUser.getTenantId(), sysUser.getUserId(), forumAuditReq.getViolationTypes(), forumAuditReq.getRemark(), forumAuditReq.getIds());

        List<String> violationTypeStringList = new ArrayList<>(forumAuditReq.getViolationTypes().size());
        for (Byte violationType : forumAuditReq.getViolationTypes()) {
            String s = SysCodeUtils.easyToGetName(SysCodeKeyConstants.FORUM_VIOLATION_TYPE, String.valueOf(violationType));
            violationTypeStringList.add(s);
        }

        //通知用户删除消息
        for (Long id : forumAuditReq.getIds()) {
            ForumCommentDto forumCommentDto = forumCommentService.selectCacheById(id);
            if (forumCommentDto != null) {
                Long householdId = forumCommentDto.getHouseholdId();
                HouseholdDto householdDto = householdService.selectCacheById(householdId);
                MobileUserDto mobileUserDto = mobileUserService.selectById(forumCommentDto.getPersonId());

                if (mobileUserDto != null) {
                    mobileUserMsgBusiness.pushMsg(
                            sysUser.getTenantId(),
                            householdDto.getVillageId(),
                            Collections.singletonList(mobileUserDto),
                            MobileUserMsgConstants.SourceType.FORUM_MSG,
                            forumCommentDto.getId(),
                            MobileUserMsgConstants.SourceType.FORUM_MSG.getDefaultTitle(),
                            "您在\"" + DateUtils.format(forumCommentDto.getCommentTime(), DateUtils.FormatType.COMMON) + "\"发布的评论因涉及" + JacksonUtils.toJsonString(violationTypeStringList) + "被管理员删除",
                            true,
                            new PushConstants.PushType[]{PushConstants.PushType.WECHAT_OFFICIAL}
                    );
                }
            }

        }

        return Response.ok();
    }


}
